package com.ruoyi.invoice.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.spring.util.WrapperUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.exception.CustomException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.invoice.domain.*;
import com.ruoyi.invoice.dto.InvoiceTemplateDTO;
import com.ruoyi.invoice.mapper.BusinessTypeMapper;
import com.ruoyi.invoice.mapper.InvoiceTemplateDetailMapper;
import com.ruoyi.invoice.vo.InvoiceTemplateDetailVO;
import com.ruoyi.invoice.vo.InvoiceTemplateVO;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.invoice.mapper.InvoiceTemplateMapper;
import com.ruoyi.invoice.service.IInvoiceTemplateService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 发票凭证模版Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-05
 */
@Service
public class InvoiceTemplateServiceImpl implements IInvoiceTemplateService
{
    @Autowired
    private InvoiceTemplateMapper invoiceTemplateMapper;

    @Autowired
    private BusinessTypeMapper businessTypeMapper;

    @Autowired
    private InvoiceTemplateDetailMapper invoiceTemplateDetailMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;



    private static final String WORD_KEY = "word:wordList";
    // 科目缓存键
    private static final String SUBJECT_KEY = "subject:subjectList";
    // 摘要缓存键
    private static final String SUMMARY_KEY = "summary:summaryList";

    /**
     * 查询发票凭证模版
     *
     * @param templateId 发票凭证模版主键
     * @return 发票凭证模版
     */
    @Override
    public InvoiceTemplateVO selectInvoiceTemplateByTemplateId(Long templateId)
    {
        return invoiceTemplateMapper.selectInvoiceTemplateByTemplateId(templateId);
    }

    /**
     * 查询发票凭证模版列表
     *
     * @param invoiceTemplate 发票凭证模版
     * @return 发票凭证模版
     */
    @Override
    public List<InvoiceTemplate> selectInvoiceTemplateList(InvoiceTemplate invoiceTemplate)
    {
        return invoiceTemplateMapper.selectInvoiceTemplateList(invoiceTemplate);
    }

    /**
     * 新增发票凭证模版
     *
     * @param invoiceTemplateDTO 发票凭证模版
     * @return 结果
     */
    @Override
    @Transactional
    public int insertInvoiceTemplate(InvoiceTemplateDTO invoiceTemplateDTO)
    {

        InvoiceTemplate invoiceTemplate = InvoiceTemplate.builder()
                .stencilCoding("PZBM" + new Date().getTime())
                .templateName(invoiceTemplateDTO.getTemplateName())
                .wordId(invoiceTemplateDTO.getWordId())
                .businessTypeId(invoiceTemplateDTO.getBusinessTypeId())
                .build();

        // 科目列表
        List<Subject> subjects = JSON.parseArray(redisTemplate.opsForValue().get(SUBJECT_KEY), Subject.class);
        List<Summary> summaries = JSON.parseArray(redisTemplate.opsForValue().get(SUMMARY_KEY), Summary.class);

        if (subjects == null || summaries == null) {
            throw new RuntimeException("科目和摘要缓存为空,请刷新页面");
        }

        List<InvoiceTemplateDetail> entries = invoiceTemplateDTO.getEntries();
        for (InvoiceTemplateDetail entry : entries) {
            // 找出借方科目名称和贷方科目名称
            if (entry.getDirection() == 0 && invoiceTemplate.getLendSubjectName() == null) {
                for (Subject subject : subjects) {
                    if (subject.getSubjectId() == entry.getSubjectId()) {
                        invoiceTemplate.setLendSubjectName(subject.getSubjectName());
                    }
                }
            } else if (entry.getDirection() == 1 && invoiceTemplate.getLoanSubjectName() == null) {
                // 找出贷方科目名称
                for (Subject subject : subjects) {
                    if (subject.getSubjectId() == entry.getSubjectId()) {
                        invoiceTemplate.setLoanSubjectName(subject.getSubjectName());
                    }
                }
            }

            if (invoiceTemplate.getSummaryName() == null) {
                for (Summary summary : summaries) {
                    if (summary.getSummaryId() == entry.getSummaryId()) {
                        invoiceTemplate.setSummaryName(summary.getSummaryContent());
                    }
                }
            }
        }

        int insert = invoiceTemplateMapper.insert(invoiceTemplate);
        if (invoiceTemplate.getTemplateId() == null) {
            throw new CustomException("系统异常：添加数据，id获取失败");
        }
        int a = 0;
        for (InvoiceTemplateDetail entry : entries) {
            entry.setTemplateId(invoiceTemplate.getTemplateId());
            a = invoiceTemplateDetailMapper.insert(entry);
        }

        if (insert > 0 && a > 0) {
            return 1;
        } else {
            return 0;
        }


    }

    /**
     * 修改发票凭证模版
     *
     * @param invoiceTemplateDTO 发票凭证模版
     * @return 结果
     */
    @Override
    @Transactional
    public int updateInvoiceTemplate(InvoiceTemplateDTO invoiceTemplateDTO)
    {
        InvoiceTemplate invoiceTemplate = InvoiceTemplate.builder().build();
        // 拆分数据 //拷贝
        BeanUtils.copyBeanProp(invoiceTemplate,invoiceTemplateDTO);
        if (invoiceTemplate.getTemplateId() == null) {
            throw new CustomException("系统异常：修改数据，id获取失败");
        }

        invoiceTemplateMapper.updateById(invoiceTemplate);

        // 删除原有的明细
        invoiceTemplateDetailMapper.delete(new QueryWrapper<InvoiceTemplateDetail>().lambda().eq(InvoiceTemplateDetail::getTemplateId, invoiceTemplate.getTemplateId()));

        List<InvoiceTemplateDetail> entries = invoiceTemplateDTO.getEntries();
        for (InvoiceTemplateDetail entry : entries) {
            if (entry.getTemplateId() == null) {
                entry.setTemplateId(invoiceTemplate.getTemplateId());
            }
            invoiceTemplateDetailMapper.insert(entry);
        }
        return 1;
    }

    /**
     * 批量删除发票凭证模版
     *
     * @param templateIds 需要删除的发票凭证模版主键
     * @return 结果
     */
    @Override
    public int deleteInvoiceTemplateByTemplateIds(Long[] templateIds)
    {
        QueryWrapper<InvoiceTemplateDetail> queryWrapper = new QueryWrapper<>();
        for (Long templateId : templateIds) {
            invoiceTemplateDetailMapper.delete(queryWrapper.lambda().eq(InvoiceTemplateDetail::getTemplateId, templateId));
        }
        return invoiceTemplateMapper.deleteInvoiceTemplateByTemplateIds(templateIds);
    }

    /**
     * 删除发票凭证模版信息
     *
     * @param templateId 发票凭证模版主键
     * @return 结果
     */
    @Override
    public int deleteInvoiceTemplateByTemplateId(Long templateId)
    {
        QueryWrapper<InvoiceTemplateDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(InvoiceTemplateDetail::getTemplateId, templateId);
        int delete = invoiceTemplateDetailMapper.delete(queryWrapper);
        return invoiceTemplateMapper.deleteInvoiceTemplateByTemplateId(templateId);
    }


    /**
     * 查询下拉框数据 凭证字  摘要  科目   业务类型
     * @return
     */
    @Override
    public Map<String, List<?>> getInvoiceTemplateList() {

        List<VoucherWord> voucherWords = JSON.parseArray(redisTemplate.opsForValue().get(WORD_KEY), VoucherWord.class);
        List<Subject> subjects = JSON.parseArray(redisTemplate.opsForValue().get(SUBJECT_KEY), Subject.class);
        List<Summary> summaries = JSON.parseArray(redisTemplate.opsForValue().get(SUMMARY_KEY), Summary.class);

        // 查询业务类型下拉框数据
        List<InvoiceBusinessType> invoiceBusinessTypes = businessTypeMapper.selectList(null);

        Map<String, List<?>> map = new HashMap<>();
        map.put("wordList", voucherWords);
        map.put("subjectList", subjects);
        map.put("summaryList", summaries);
        map.put("businessTypeList", invoiceBusinessTypes);
        return map;
    }

    /**
     * 预览
     * @param templateId
     * @return
     */
    @Override
    public List<InvoiceTemplateDetailVO> getTemplateDetail(Long templateId) {
        List<InvoiceTemplateDetailVO> list = invoiceTemplateDetailMapper.selectInvoiceTemplateDetailVO(templateId);
        return list;
    }




}
